package com.ktgj.customer.controller;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ktgj.common.core.exception.LoginException;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.domain.Bank;
import com.ktgj.customer.domain.Customer;
import com.ktgj.customer.domain.vo.BankCardVo;
import com.ktgj.customer.domain.vo.BankCareDto;
import com.ktgj.customer.domain.vo.BankInformation;
import com.ktgj.customer.domain.vo.BankVo;
import com.ktgj.customer.service.IBankService;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.customer.util.CheckBankCard;
import com.ktgj.customer.util.Clients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.customer.domain.BankCard;
import com.ktgj.customer.service.IBankCardService;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 银行卡信息Controller
 * 
 * @author ruoyi
 * @date 2021-09-01
 */
@ControllerAdvice
@RestController
@RequestMapping("/bankCard")
public class BankCardController extends BaseController
{
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private IBankService bankService;

    /**
     * 获取当前用户的ID
     * @param request
     * @return
     */

    public Long customerId(HttpServletRequest request){
        Long customerId = loginService.getLoginCustomer(request).getCustomerId();
        return customerId;
    }

    /**
     * 查询银行卡信息列表
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:list")
    @GetMapping("/list")
    public TableDataInfo list(BankCard bankCard)
    {
        startPage();
        List<BankCard> list = bankCardService.selectBankCardList(bankCard);
        return getDataTable(list);
    }

    /**
     * 导出银行卡信息列表
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:export")
    @Log(title = "银行卡信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BankCard bankCard) throws IOException
    {
        List<BankCard> list = bankCardService.selectBankCardList(bankCard);
        ExcelUtil<BankCard> util = new ExcelUtil<BankCard>(BankCard.class);
        util.exportExcel(response, list, "银行卡信息数据");
    }

    /**
     * 获取银行卡信息详细信息
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:query")
    @GetMapping(value = "/{bankCardId}")
    public AjaxResult getInfo(@PathVariable("bankCardId") Long bankCardId)
    {
        return AjaxResult.success(bankCardService.selectBankCardById(bankCardId));
    }

    /**
     * 新增银行卡信息
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:add")
    @Log(title = "银行卡信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BankCard bankCard)
    {
        return toAjax(bankCardService.insertBankCard(bankCard));
    }

    /**
     * 修改银行卡信息
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:edit")
    @Log(title = "银行卡信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BankCard bankCard)
    {
        return toAjax(bankCardService.updateBankCard(bankCard));
    }

    /**
     * 删除银行卡信息
     */
    //@PreAuthorize(hasPermi = "customer:bankCard:remove")
    @Log(title = "银行卡信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{bankCardIds}")
    public AjaxResult remove(@PathVariable Long[] bankCardIds)
    {
        return toAjax(bankCardService.deleteBankCardByIds(bankCardIds));
    }


    /**
     * 当前用户已绑定的银行卡列表
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("/boundBankCardList")
    public AjaxResult boundBankCardList(HttpServletRequest request) {
        Long memberId;
        try {
            memberId = customerId(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        List<BankCardVo> bankCardVos;
        try {
            bankCardVos = bankCardService.selectBankCardByMemberIdList(memberId);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (bankCardVos != null && bankCardVos.size() > 0){
             return AjaxResult.success(bankCardVos);
        }
        else {
            return AjaxResult.error("查询失败");
        }
    }

    /**
     * 会员已绑定信用卡
     * */
    @PostMapping("/creditCardList")
    public AjaxResult creditCardList(@RequestBody Map<String, Object> map){
        if (map.get("customerId") != null && !map.get("customerId").equals("")){
            Long customerId = Long.valueOf(map.get("customerId").toString());
            List<BankCardVo> bankCardVos = bankCardService.creditCardList(customerId);
            if (bankCardVos != null && bankCardVos.size() > 0){
                return AjaxResult.success(bankCardVos);
            }
            else {
                return null;
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 当前用户添加银行卡信息
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("/insertBankCardInformation")
    public AjaxResult insertBankCardInformation(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        Customer temporaryCustomer;
        try {
            temporaryCustomer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        BankCard bankCard =new BankCard();
        String cardNumber;
        String obligatePhone;
        String verificationCode;
        String bankName;
        String cardType;
        String cardholder;
        String idType;
        String ownerCdid;
        if (map.get("cardNumber") != null && !map.get("cardNumber").equals("") &&
                map.get("obligatePhone") != null && !map.get("obligatePhone").equals("") &&
                map.get("verificationCode") != null && !map.get("verificationCode").equals("") &&
                map.get("bankName") != null && !map.get("bankName").equals("") &&
                map.get("cardType").toString() != null && !map.get("cardType").toString().equals("") &&
                map.get("cardholder") != null && !map.get("cardholder").equals("") &&
                map.get("idType") != null && !map.get("idType").equals("") &&
                map.get("ownerCdid") != null && !map.get("ownerCdid").equals("")){
            cardNumber = map.get("cardNumber").toString();
            obligatePhone = map.get("obligatePhone").toString();
            verificationCode = map.get("verificationCode").toString();
            bankName = map.get("bankName").toString();
            cardType = map.get("cardType").toString();
            cardholder = map.get("cardholder").toString();
            idType = map.get("idType").toString();
            ownerCdid = map.get("ownerCdid").toString();
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }

        Customer customer;
        try {
            customer = loginService.customerPhoneLogin(obligatePhone, verificationCode);
        }catch (Exception e){
            return AjaxResult.error("验证失败");
        }

        Bank bank = bankService.selectBankLike(bankName);
        if (customer != null) {
            bankCard.setMemberId(temporaryCustomer.getCustomerId());
            bankCard.setCardNumber(cardNumber);
            bankCard.setObligatePhone(obligatePhone);
            bankCard.setBankId(bank.getBankId());
            bankCard.setBankName(bank.getBankName());
            bankCard.setCardholder(cardholder);
            bankCard.setIdType(idType);
            bankCard.setOwnerCdid(ownerCdid);

            if (cardType.equals("creditcard")){
                String creditCardTime = map.get("creditCardTime").toString();
                Long cvv2 = Long.valueOf(map.get("cvv2").toString());

                bankCard.setCreditCardTime(creditCardTime);
                bankCard.setCvv2(cvv2);
            }
            bankCard.setCardType(cardType);
            return AjaxResult.success(bankCardService.insertBankCardByMemberId(bankCard));
        } else {
            return AjaxResult.error("01001", "验证码输入错误");
        }
    }

    /**
     * 银行卡短信验证码发送接口
     */
    @PostMapping(value = "/verificationSmsLoginCode")
    public AjaxResult verificationSmsLoginCode(@RequestBody Map<String, Object> map) {
        String phone = map.get("phone").toString();
        String cardNumber = map.get("cardNumber").toString();

        CheckBankCard checkBankCard = new CheckBankCard();
        if (checkBankCard.checkBankCard(cardNumber)){
            String state;
            try {
                state = loginService.smsLoginCode(phone);
            } catch (Exception e){
                e.printStackTrace();
                return AjaxResult.error("验证码发送失败");
            }

            if (state.equals("success")) {
                return AjaxResult.success();
            } else if (state.equals("limit")) {
                return AjaxResult.error("今日发送验证码次数已达上限");
            } else {
                return AjaxResult.error("验证码发送失败，请重试");
            }
        }
        else {
            return AjaxResult.error("无效银行卡");
        }
    }

    /**
     * 银行卡类型集合
     * */
    @PostMapping("/bankCardType")
    public AjaxResult bankCardType(){
        List<BankVo> bankVoList = bankCardService.selectBankVo();
        if (bankVoList != null){
            return AjaxResult.success(bankVoList);
        }
        else {
            return AjaxResult.error("获取银行卡类型失败");
        }
    }

    /**
     * 通过银行卡号获取银行信息
     * */
    @PostMapping("/bankName")
    public AjaxResult bankName(@RequestBody Map<String, Object> map) {
        String cardNumber = map.get("cardNumber").toString();
        Bank bank;
        try {
            bank = bankCardService.selectBankByBankCode(cardNumber);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (bank != null){
            return AjaxResult.success(bank);
        }
        else {
            return AjaxResult.error("未查到数据");
        }
    }

    /**
     * 通过银行卡号获取银行信息(远程)
     * */
    @PostMapping("/bankNames")
    public Bank bankNames(@RequestBody Map<String, Object> map) {
        String cardNumber = map.get("cardNumber").toString();
        Bank bank;
        try {
            bank = bankCardService.selectBankByBankCode(cardNumber);
        } catch (Exception e){
            return null;
        }

        return bank;
    }

    /**
     * 根据id查询会员已绑定银行卡信息
     * */
    @PostMapping("/selectBankCardBytBankCardId")
    public BankCard selectBankCardBytBankCardId(@RequestParam("bankCardId") Long bankCardId){
        return bankCardService.selectBankCardBytBankCardId(bankCardId);
    }

    /**
     * 会员已绑定银行卡列表（远程）
     * */
    @PostMapping("/selectBankCardByMemberId")
    public List<BankCard> selectBankCardByMemberId(@RequestBody Map<String, Object> map){
        Long memberId = Long.valueOf(map.get("memberId").toString());
        List<BankCard> bankCardList;
        try {
            bankCardList = bankCardService.selectBankCardByMemberId(memberId);
        } catch (Exception e){
            return null;
        }
        return bankCardList;
    }

    /**
     * 火车票银行卡支付查询银行卡信息
     * */
    @PostMapping("/backCardNum")
    public BankCard backCardNum(@RequestBody String cardNumber) {
        BankCard bankCard = bankCardService.backCardNum(cardNumber);
        return bankCard;
    }

    /**
     * 后端——查询银行卡
     * */
    @PostMapping("/backSelectCard")
    public AjaxResult backSelectBankCard(@RequestBody Map<String, Object> map){
        if (map.get("memberId") != null && !map.get("memberId").equals("")){
            String type = null;
            if (map.get("type") != null && !map.get("type").equals("")){
                type = map.get("type").toString();
            }
            Long memberId = Long.valueOf(map.get("memberId").toString());
            List<BankCareDto> bankCareDtoList;
            try {
                bankCareDtoList = bankCardService.backSelectBankCard(memberId, type);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (bankCareDtoList.size() > 0){
                return AjaxResult.success(bankCareDtoList);
            }
            else {
                return AjaxResult.error("未查到数据");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——查询待修改银行卡
     * */
    @PostMapping("/backBankCardById")
    public AjaxResult backSelectBankCardById(HttpServletRequest request, @RequestBody Map<String, Object> map){
        if (map.get("bankCardId") != null && !map.get("bankCardId").equals("")){
            Long bankCardId = Long.valueOf(map.get("bankCardId").toString());

            Long memberId = null;
            if (map.get("memberId") != null && !map.get("memberId").equals("")){
                memberId = Long.valueOf(map.get("memberId").toString());
            }

            BankCareDto bankCareDto;
            try {
                bankCareDto = bankCardService.backSelectBankCardById(bankCardId, memberId);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (bankCareDto != null){
                return AjaxResult.success(bankCareDto);
            }
            else {
                return AjaxResult.error("未查到数据");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——新增银行卡
     * */
    @PostMapping("/backInsertBankCard")
    public AjaxResult backInsertBankCard(@RequestBody BankCareDto bankCareDto){
        if (bankCareDto != null){
            try {
                bankCardService.backInsertBankCard(bankCareDto);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            return AjaxResult.success(bankCareDto);
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 新增银行卡（远程）
     * */
    @PostMapping("/bankCard")
    public int bankCard(@RequestBody BankCard bankCard){
        bankCardService.insertBankCard(bankCard);
        return Math.toIntExact(bankCard.getBankCardId());
    }

    /**
     * 后端——修改银行卡
     * */
    @PostMapping("/backUpdateBankCard")
    public AjaxResult backUpdateBankCard(@RequestBody BankCareDto bankCareDto){
        if (bankCareDto != null){
            int i;
            try {
                i = bankCardService.backUpdateBankCard(bankCareDto);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (i > 0){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.error("修改失败");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——删除银行卡
     * */
    @PostMapping("/backDeleteBankCard")
    public AjaxResult backDeleteBankCard(@RequestBody Map<String, Object> map){
        if (map.get("bankCardId") != null && !map.get("bankCardId").equals("")){
            Long bankCardId = Long.valueOf(map.get("bankCardId").toString());
            int i;
            try {
                i = bankCardService.backDeleteBankCard(bankCardId);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (i > 0){
                return AjaxResult.success("删除成功");
            }
            else {
                return AjaxResult.error("删除失败");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    @PostMapping("selectBackCardNum")
    public BankCard selectBackCardNum(@RequestBody Map<String, Object> map) {
        if (map.get("memberId") != null && !map.get("memberId").equals("") &&
                map.get("cardNumber") != null && !map.get("cardNumber").equals("")){
            Long memberId = Long.valueOf(map.get("memberId").toString());
            String cardNumber = map.get("cardNumber").toString();
            BankCard bankCard = bankCardService.selectBackCardNum(memberId, cardNumber);
            return bankCard;
        }
        else {
            return null;
        }
    }

    /**
     * 卡号查银行代码
     * */
    @PostMapping("/backCard")
    public String backCard(@RequestBody Map<String, Object> map) {
        if (map.get("cardNumber") != null && !map.get("cardNumber").equals("")){
            String cardNumber = map.get("cardNumber").toString();
            try {
                String s = bankCardService.backCard(cardNumber);
                return s;
            } catch (Exception e){
                return null;
            }
        }
        else {
            return null;
        }
    }
}
